function [error] = main_pulsar_potato(window,shift,src_folfer,FileList,draw_fig,frequencies,apply_filter_before)

%% segement all the files

Fs = 2000;

%window should divide 4
%window = 3000/2800; % very good results with marion 20
%window = 4400; % very good results with nikole 40
%window = 3000; % very good results with david 20
%window = 2600; % very good results with chloe 40
%window = 3000; % in samples
%shift = 100; %this helps with Marion shift=100
start_of_class = [];
end_of_class = [];

is_pulsar_single_trigger_channel_from_eeglab = false;

potatos = [];
windows = [];
%load('d:\windows.mat','windows');

for curFileIx = 1:length(FileList)
    
    %window = windows(m);
        %Instead of file the data is obtained from EEGLAB 
        if (is_pulsar_single_trigger_channel_from_eeglab)
            
%             FileList = {'EEGLAB data'};
%             data = EEG.data'; 
%             Fs = EEG.srate;
%             
%             datar = data(:,1:size(data,2)-1); % remove 1 trigger channel at the end
% 
%             trigger_channel = data(:, size(data,2));
% 
%             classN = length(count_sequence(trigger_channel,2)); % "2" tags each class
% 
%             classRest = classN; % the rest class is always the last
% 
%             trialsN = length(count_sequence(trigger_channel,1));  % "1" tags each trial
            
        else   
            
            load([src_folfer FileList{curFileIx}]);
            disp(['Subject file:' FileList{curFileIx}]);
            
            datar = data(:,1:size(data,2)-2); % remove 2 trigger channel at the end and leaves only the EMG/EEG channels

            %trial_channel = data(:,8);
            trial_channel = data(:, size(data,2)-1);

            %class_separation_channel = data(:,9);
            class_separation_channel = data(:, size(data,2));

            classN = length(count_sequence(class_separation_channel,5));  % "5" tags each class

            %classN = 2;
            
            classRest = classN; % the rest class is always the last

            trialsN = length(count_sequence(trial_channel,5));  % "5" tags each trial
            
            %% filtering
            if (length(frequencies)>0)
            
                [b,a] = build_filter_multipe_bandpass(Fs,frequencies);
                
                if (apply_filter_before)
                    datar = filtfilt(b,a,datar);
                else
                  dataf = filtfilt(b,a,datar);
                  datar = [datar dataf];
                end;
            end;
            
        end;
        
        disp(['Classes/Movements detected: ' int2str(classN)]);
        disp(['Total trails detected: ' int2str(trialsN)]);
        disp(['Frequency: ' int2str(Fs)]);

        for m = 1:classN

            %classes should be supplied to this function
            %select only the trials for this class
            %"best_index" - in 1 shows the postion of a trial, "best_trigger" -
            %again shows the postion but in the range 1 .. n
            if (is_pulsar_single_trigger_channel_from_eeglab)
               %Pulsar GTEC
               [best_index,best_trigger] = generate_trials_postitions_using_single_discrete_channel(m, trigger_channel, 1, 2);
            else
               %Pulsar BIOPAC 
               %[best_index,best_trigger,class_start_pos,class_end_pos] = generate_trials_postitions_using_discrete_channel(m, trial_channel,class_separation_channel);
               [best_index1,best_trigger1,class_start_pos,class_end_pos] = generate_trials_postitions_using_discrete_channel(m, trial_channel,class_separation_channel);
               best_index = best_index1;
               start_of_class = [start_of_class class_start_pos];
               end_of_class = [end_of_class class_end_pos];
               % calculate the  good size of the sliding window
%                [best_index2,best_trigger2] = generate_trials_postitions_auto(Fs, datar, 20 , class_start_pos, class_end_pos);
%                best_trigger = best_trigger2(1:length(best_trigger1))' & best_trigger1;
%                
%                window = mean(count_sequence(best_trigger, 1)) %in samples
%                window = floor(window);
%                
%                windows = [windows window];
              
            end;
            
            trials_per_class = zeros(size(datar,2),window,length(best_index));
            disp(['Train trials: ' int2str(length(best_index)) ' ' FileList{curFileIx}])

            %get the data for these triggers
            for i=1:length(best_index)
                %calculate a range around the trigger
                
                trials_per_class(:,:,i) = datar(best_index(i)+shift:best_index(i)+shift+window-1,:)';
            end

         
            %% Training 
            X = trials_per_class;
            
            TrainCOV = covariances(X);
            
            [C, th] = potato_estimation_iterativ(TrainCOV);
            
            potato.classNumber = m;
            potato.baryCenter = C;
            potato.threshold = th;
            
            potatos = [potatos potato];
            
        end;
   
    disp('--------------------------------');% next file
end

%% Preparing for Classification over X and Y

overlap = window-window/8;

Nt = size(datar,1);

tcov = (window-overlap)/(Fs):(window-overlap)/(Fs):(Nt-window)/Fs;
[COVtest CovTestIndex] = eeg2cov_index(datar',window,overlap);
t = 1/Fs:1/Fs:Nt/Fs;

disp(['Test trials: ' int2str(length(COVtest))]);

result = zeros(length(COVtest),1);
classAdjustmentsCount = 0;

%% Classification

%for i = 1:length(potatos)
for i = 1:length(COVtest)

    %window = windows(i);
    
    min_norm_dist = 1000; % minimum normalized distance
    best_class = 0;
    
    XTest = COVtest(:,:,i);
    
    for m = 1:(length(potatos))
        
        [~,d] = potato_detection(XTest,potatos(m).baryCenter,potatos(m).threshold);
        
        th = potatos(m).threshold;
        
        if (d < th) % it is in the class, distance is less than the threshold
            
            %check for better class
            norm_dist = d / th; % normalize
            
            if (norm_dist < min_norm_dist)
                
                 if (min_norm_dist ~= 1000) % we found a change between two classes and not a simple assignment of change
                     %disp(['Class adjusted from ' int2str(best_class) ' to ' int2str(m)]);
                     classAdjustmentsCount = classAdjustmentsCount + 1;
                 end;
                 
                 min_norm_dist = norm_dist;
                 best_class = m;
            end;
        end;
    end;
    
    if (best_class == 12) 
        best_class = 0; 
    end;
    
%     if (best_class ~= 2) 
%         best_class = 0; 
%     end;
     
    result(i) = best_class;
end;

%% error calculation and plotting
set_opengl_renderer();

if (draw_fig)
  figure;
  hist(result,[1:classN]);

  figure;
end;

error = 0;
for m = 1:(length(potatos)-1)
    
    k = 0;
    single_result = result;
    single_result(single_result~=m) = 0;
    
    subplot(3,4,m);
    if (draw_fig)
       plot(t,trial_channel/10,'k'); % original trials 
    end;
    hold on;
    minnn = min (length(tcov),length(single_result));
    if (draw_fig)
       plot(tcov,single_result(1:minnn),'r');
    end;
    
    for i = 1:length(single_result)
        if (result(i)==m && CovTestIndex(i) >= start_of_class(m) && CovTestIndex(i)<end_of_class(m))
            k = k + 1;
        end;
    end;
    
    acc = k / sum(result==m);
    error = error +  sum(result==m) - k;
    disp(['class ' num2str(m) ' accuracy: ' int2str(acc*100) '%']);


end;

classAdjustmentsCount

disp(['error ' num2str(error)]);
%
            
%mean(windows)